#! python3
#-*- coding: UTF-8 -*-
import os, sys

# Compute location from command line arguments.eg: x_layout.xml

if len(sys.argv) < 2:
	print('Usage: create.py layout.xml')
	sys.exit()

#====================== func =======================
def createLayout(layout):
	try:
		print("createLayout:%s" % layout)
		cwd=os.getcwd()
		print '*** new working dir'
		print cwd
		fobj=open(layout+'.xml','w')
		fobj.write('<!-- --> \n<?xml version="1.0" encoding="utf-8"?>')
		fobj.write('<RelativeLayout   \n\
	    xmlns:android="http://schemas.android.com/apk/res/android"   \n\
	    android:layout_width="match_parent"   \n\
	    android:layout_height="match_parent">   \n\
	      \n\
	    <include layout="@layout/titlebar"/>  \n\
	      \n\
	    <android.support.v4.widget.SwipeRefreshLayout  \n\
	        android:id="@+id/swipe_refresh_layout"  \n\
	        android:layout_width="match_parent"  \n\
	        android:layout_height="match_parent"  \n\
	        android:layout_below="@id/titlebar">  \n\
	          \n\
	        <android.support.v7.widget.RecyclerView  \n\
	            android:id="@+id/recycler_view"  \n\
	            android:layout_width="match_parent"  \n\
	            android:layout_height="match_parent"/>  \n\
	    </android.support.v4.widget.SwipeRefreshLayout>  \n\
	      \n\
	    <include  \n\
	        layout="@layout/default_loading_container"  \n\
	        android:layout_width="match_parent"  \n\
	        android:layout_height="match_parent"  \n\
	        android:layout_below="@id/titlebar"/>  \n\
	          \n\
	</RelativeLayout>')
		fobj.close()
	except Exception , e:
		print("create layout error.", e)

def createFragment(layout, fn, viewHelper, viewModel):
	try:
		print("createFragment:%s" % fn)
		fobj=open(fn+'.java','w')
		fobj.write('\xEF\xBB\xBF')
		fobj.write('public class ')
		fobj.write(fn)
		fobj.write(' extends BaseFragment implements View.OnClickListener { \n \n')
		fobj.write('private SwipeRefreshLayout mSwipeRefreshLayout;  \n\
	    private RecyclerView mRecyclerView;  \n\
	    private SQRecyclerViewHelper mRecyclerViewHelper;  \n\
	    private GJHeaderAndFooterRecyclerAdapter<XX> mListAdapter;  \n\
	    private SQListMoreView mListMoreView;  \n')
		fobj.write('private '+viewModel+' mMainViewModel;  \n')
		fobj.write('private String nextParams;  \n\
	    private boolean hasNextPage;  \n\
	      \n\
	    @Override  \n\
	    public void onCreate(Bundle savedInstanceState) {  \n\
        super.onCreate(savedInstanceState); \n')
		fobj.write('mMainViewModel = ViewModelProviders.of(getActivity()).get('+viewModel+'.class); \n')
		fobj.write('}  \n')
		fobj.write('@Override  \n\
	    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  \n\
	        View view = inflater.inflate(R.layout.'+ layout + ', null);  \n\
			 \n\
	        mSwipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);  \n\
	        mSwipeRefreshLayout.setColorSchemeColors(Color.parseColor("#39BC30"));  \n\
	          \n\
	        mRecyclerViewHelper = new SQRecyclerViewHelper();  \n\
	        mRecyclerViewHelper.initView(view, null);  \n\
	        mRecyclerView = mRecyclerViewHelper.mRecyclerView;  \n\
	          \n\
	        mRecyclerViewHelper.getNoDataContainer().setOnClickListener(this);  \n\
	          \n\
	        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);  \n\
	        mListAdapter = new GJHeaderAndFooterRecyclerAdapter<XX>(getActivity()) {  \n\
	          \n\
	            @Override  \n\
	            public GJBaseRecyclerViewHolder<XX> doCreateViewHolder(ViewGroup parent, int viewType) {  \n\
	                ViewHolder holder = null;  \n\
	                View view = mInflater.inflate(R.layout.item_xx, parent, false);  \n\
	                  \n\
	                holder = new ViewHolder(view);  \n\
	                  \n\
	                return holder;  \n\
	            }  \n\
	              \n\
	            @Override  \n\
	            public void doBindViewHolder(GJBaseRecyclerViewHolder holder, int position) {  \n\
	                long start = SystemClock.uptimeMillis();  \n\
	                XX data = mData.get(position - getHeadersCount());  \n\
	                ((ViewHolder) holder).onBind(data, position, null);  \n\
	                  \n\
	                //DLog.printTime("bind", SystemClock.uptimeMillis() - start, " bindView");  \n\
	            }  \n\
	        };  \n\
	        mRecyclerView.addItemDecoration(new SpacesItemDecoration(DisplayUtils.dipToPixel(5), DisplayUtils.dipToPixel(5)));  \n\
	        mRecyclerView.setLayoutManager(linearLayoutManager);  \n\
	        mRecyclerView.setAdapter(mListAdapter);  \n\
	          \n\
	        mListMoreView = new SQListMoreView(mRecyclerView, R.layout.item_list_more);  \n\
	          \n\
	        mListAdapter.addFootView(mListMoreView.getLoadMoreView());  \n\
	        mRecyclerViewHelper.addScrollListener(mListMoreView, mListAdapter.getFootersCount(), mListAdapter, () -> {  \n\
	            mListMoreView.onLoadingStateChanged(IMoreView.STATE_LOADING);  \n\
	            int page = mMainViewModel.getPage() + 1;  \n\
	            if (page < 1) {  \n\
	                page = 1;  \n\
	            }  \n\
	            //loadmore  \n\
	        });  \n\
	          \n\
	        mRecyclerViewHelper.showLoadingForNetwork();  \n\
	          \n\
	        mSwipeRefreshLayout.setOnRefreshListener(() -> {  \n\
	            mListMoreView.onLoadingStateChanged(IMoreView.STATE_LOADING);  \n\
	            mMainViewModel.setPage(0);  \n\
	            nextParams = null;  \n\
	            hasNextPage = true;  \n\
	            //refresh  \n\
	        });  \n\
	          \n\
	        return view;  \n\
	    }    \n\n')
		fobj.write('@Override  \n\
	    public void onClick(View view) {  \n\
	        int id = view.getId();  \n\
	        if (view.getId() == R.id.nodata_container) {  \n\
	            mRecyclerViewHelper.showLoadingForNetwork();  \n\
	              \n\
	            nextParams = null;  \n\
	            hasNextPage = true;  \n\
	              \n\
	        }  \n\
	    }  \n\
	      \n\
	    @Override  \n\
	    public void onActivityCreated(Bundle savedInstanceState) {  \n\
	        super.onActivityCreated(savedInstanceState);  \n\
	        //observer  \n\
	        observerXX();  \n\
	        //load  \n\
	        loadXX();  \n\
	    }\
	      \n\
	    private void loadXX() {  \n\
	        mMainViewModel.loadXX();  \n\
	    }  \n\
	      \n\
	    private void observerXX() {  \n\
	        mMainViewModel.getXXLiveData().observe(this, resource -> {  \n\
	            if (resource != null) {  \n\
	                processResource(resource);  \n\
	            }  \n\
	        });  \n\
	    }  \n\
	      \n\
	    private void processResource(Resource<YY> resource) {  \n\
	        switch (resource.status) {  \n\
	            case LOADING:  \n\
	                break;  \n\
	            case API_ERROR:  \n\
	                mSwipeRefreshLayout.setRefreshing(false);  \n\
	                ToastUtils.showToast(resource.message);  \n\
	                if (mListAdapter.getRealItemCount() > 0) {  \n\
	                    mListMoreView.onLoadingStateChanged(IMoreView.STATE_LOAD_FAIL);  \n\
	                    updateCommonViewState(STATE_HAS_DATA);  \n\
	                } else {  \n\
	                    mListMoreView.onLoadingStateChanged(IMoreView.STATE_LOAD_FAIL);  \n\
	                    updateCommonViewState(STATE_NODATA_NETWORK_NO_POST);  \n\
	                }  \n\
	                break;  \n\
	            case NET_ERROR:  \n\
	                mSwipeRefreshLayout.setRefreshing(false);  \n\
	                if (mListAdapter.getRealItemCount() > 0) {  \n\
	                    mListMoreView.onLoadingStateChanged(IMoreView.STATE_LOAD_FAIL);  \n\
	                    updateCommonViewState(STATE_HAS_DATA);  \n\
	                } else {  \n\
	                    mListMoreView.onLoadingStateChanged(IMoreView.STATE_LOAD_FAIL);  \n\
	                    updateCommonViewState(STATE_NODATA_NETWORK_FAIL);  \n\
	                }  \n\
	                break;  \n\
	            case SUCCESS:  \n\
	                mSwipeRefreshLayout.setRefreshing(false);  \n\
	                boolean isFirstPage = mMainViewModel.getPage() == 0;  \n\
	                onSuccess(isFirstPage, resource.data);  \n\
	                break;  \n\
	        } \n')
		fobj.write('protected void onSuccess(boolean isFirstPage, YY videoList) {  \n\
	        if (videoList != null) {  \n\
	            nextParams = videoList.nextParams;  \n\
	        } \n\
	        //if (videoList == null || null == videoList.feedList || videoList.feedList.size() < 1) {  \n\
	        //    if (mListAdapter.getRealItemCount() > 0) {  \n\
	        //        mListMoreView.onLoadingStateChanged(IMoreView.STATE_NO_MORE);  \n\
	        //        updateCommonViewState(STATE_HAS_DATA);  \n\
	        //    } else {\
	        //        mListMoreView.onLoadingStateChanged(IMoreView.STATE_NORMAL);  \n\
	        //        updateCommonViewState(STATE_NODATA_NETWORK_NO_POST);  \n\
	        //    }  \n\
	        //    this.hasNextPage = false;  \n\
	        //    return;  \n\
	        //}  \n\
	        //this.hasNextPage = videoList.hasNextPage;  \n\
	        //if (isFirstPage) {  \n\
	        //    mListAdapter.setData(videoList.feedList);  \n\
	        //} else {  \n\
	        //    mListAdapter.addData(videoList.feedList);  \n\
	        //}  \n\
	        mListAdapter.notifyDataSetChanged();  \n\
	        mMainViewModel.setPage(mMainViewModel.getPage() + 1);  \n\
	          \n\
	        updateCommonViewState(STATE_HAS_DATA);  \n\
	        if (hasNextPage) {  \n\
	            mListMoreView.onLoadingStateChanged(IMoreView.STATE_NORMAL);  \n\
	        } else {  \n\
	            mListMoreView.onLoadingStateChanged(IMoreView.STATE_NO_MORE);  \n\
	        }  \n\
	    }  \n\
	      \n\
	    protected void updateCommonViewState(int state) {  \n\
	        switch (state) {  \n\
	            case STATE_HAS_DATA:  \n\
	                mRecyclerViewHelper.showDataView(true, 0, 0, null);  \n\
	                break;  \n\
	            case STATE_LOADING_FOR_NET:  \n\
	                mRecyclerViewHelper.showLoadingForNetwork();  \n\
	                break;  \n\
	            case STATE_NODATA_NETWORK_FAIL:  \n\
	                mRecyclerViewHelper.showNoDataViewForNetworkFailed();  \n\
	                break;  \n\
	            case STATE_NODATA_NETWORK_NO_POST:  \n\
	                mRecyclerViewHelper.showNoDataViewForNoPost(true, null, null);  \n\
	                break;  \n\
	            case STATE_NODATA_LOCATION_FAIL:  \n\
	                mRecyclerViewHelper.showNoDataViewForLocateFailed();  \n\
	                break;  \n\
	            default:  \n\
	                break;  \n\
	        }  \n\
	    }\n')
		fobj.write('}')
		fobj.close()
	except Exception , e:
		print("create fragment error.", e)

def createViewModel(fn):
	try:
		print("createViewModel:%s" % fn)
		fobj=open(fn+'.java','w')
		fobj.write('\xEF\xBB\xBF')
		fobj.write('public class ')
		fobj.write(fn)
		fobj.write(' extends ViewModel { \n \n')
		fobj.write('private final MutableLiveData<Request> xx = new MutableLiveData<>();  \n\
		  \n\
	    private LiveData<Resource<YY>> xxLiveData;  \n\
	    private Repository repository;  \n\
	      \n\
	    /**  \n\
	     * 默认是0,起始页是1,当数据获取完成后,这个值+1.表示当前页.  \n\
	     */  \n\
	    private int page = 0;')
		fobj.write('public ')
		fobj.write(fn)
		fobj.write(' {')
		fobj.write('repository = Repository.getInstance();  \n\
		  \n\
        xxLiveData = Transformations.switchMap(xx, input -> repository.getXX(input));  \n\
	    }  \n\
	      \n\
	    public int getPage() {  \n\
	        return page;  \n\
	    }  \n\
	      \n\
	    public void setPage(int page) {  \n\
	        this.page = page;  \n\
	    } \n\
	      \n\
	    public LiveData<Resource<YY>> getXXLiveData() {  \n\
	        return xxLiveData;  \n\
	    }  \n\
	      \n\
	    public void loadXX(Request request) {  \n\
	        xx.setValue(request);  \n\
	    }  \n\
		}')
		fobj.close()
	except Exception , e:
		print("create layout error.", e)

def createViewHelper(fn):
	print("createViewHelper:%s" % fn)
#====================== invoke =======================

layout = ' '.join(sys.argv[1:2])
createLayout(layout)

try:
	fname=' '.join(sys.argv[2:3])
	print("layoutname:", fname)
	xx=fname.capitalize()
	fragmentName = fname.capitalize()+'Fragment'
	viewHelper = xx+"RecyclerViewHelper"
	viewModel = xx+"ViewModel"
	print("fragmentName:", fragmentName)

	createFragment(layout, fragmentName, viewHelper, viewModel)

	createViewModel(viewModel)

	#createViewHelper(viewHelper)
except Exception , e:
	print("create error.", e)

